﻿#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
#include <Windows.h>
#include <WS2tcpip.h>

int main()
{
	//1.确定协议版本
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
	{
		printf("请求的协议版本不是2.2版本!\n");
		//9.清理协议信息
		WSACleanup();
		return -1;
	}

	//2.创建socket
	SOCKET sSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (SOCKET_ERROR == sSocket)
	{
		printf("创建socket失败:%d\n", GetLastError());
		return -2;
	}
	printf("创建socket成功\n");

	//3.确定服务器的协议地址簇
	SOCKADDR_IN addr = { 0 };
	addr.sin_family = AF_INET;//和socket函数第一个参数保持一致
	//addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//本地ip地址
	inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr.S_un.S_addr);//vs2013版本以上使用新的函数转换IP地址
	addr.sin_port = htons(10086);//大小端转换

	//4. 连接服务器
	int r = connect(sSocket, (sockaddr*)&addr, sizeof addr);
	if (-1 == r)
	{
		printf("连接服务器失败:%d\n",GetLastError());
		return -2;
	}
	printf("连接服务器成功\n");

	//5. 通信
	char buff[256];
	while (1)
	{
		memset(buff, 0, 256);//清空数组
		printf("请输入你要传输的内容: ");
		scanf("%s", buff);
		send(sSocket, buff, strlen(buff), NULL);//发送给服务器
	}

	

	while (1);//停顿
	return 0;
}